package com.jijia.webbase.interception.websocket;

import com.jijia.webbase.config.security.SaveLoginUser;
import com.jijia.webbase.utils.JwtUtil;
import com.jijia.webbase.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class WebsocketInterceptionForConfig implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        log.debug("websocket被拦截了！");
        HashMap<String, Object> threadLocal = ThreadLocalUtil.get();
        Boolean validationTokenStatus = (Boolean)threadLocal.get("validationTokenStatus");
        if (!validationTokenStatus){
            log.error("当前无token或token已失效或过期！");
            return false;
        }
        //使用 base 64 解密token，获取用户信息，并放入线程池中，方便后续使用
        log.debug("token验证通过！");
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
